/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.compress;

import cn.ac.iie.di.global.GlobalParas;
import cn.ac.iie.di.tools.FileTools;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;

/**
 *
 * @author wanglin
 */
public class TarFilePath implements Runnable {

    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(TarFilePath.class.getName());
    SimpleDateFormat simp = new SimpleDateFormat("yyyyMMddHH");
    public ArrayBlockingQueue<String> tarPool = null;
    private boolean isQuit = false;
    private String dataType = "";

    public TarFilePath(ArrayBlockingQueue<String> tarPool, String dataType) {
        this.tarPool = tarPool;
        this.dataType = dataType;
    }

    public static Boolean tar(String tarPath, String srcPath) throws Exception {
        Boolean type = null;
        try {
            File f = new File(tarPath);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(tarPath));
            File of = new File(srcPath);
            List<String> ofs = listFile(of);
            for (String off : ofs) {
                logger.info("tar file " + tarPath + " file is " + off);
                BufferedInputStream bis = null;
                try {
                    String offName = off.replaceAll(StringEscapeUtils.escapeJava(srcPath), "");
                    TarArchiveEntry tae = new TarArchiveEntry(offName);
                    tae.setSize(new File(off).length());
                    taos.putArchiveEntry(tae);
                    bis = new BufferedInputStream(new FileInputStream(off));
                    int count;
                    byte data[] = new byte[1024];
                    while ((count = bis.read(data, 0, 1024)) != -1) {
                        taos.write(data, 0, count);
                    }
//                    bis.close();
//                    taos.closeArchiveEntry();
                } catch (Exception ex) {
                    logger.warn(ex, ex);
                } finally {
                    try {
                        if (bis != null) {
                            bis.close();
                        }
                        if (taos != null) {
                            taos.closeArchiveEntry();
                        }

                    } catch (Exception ex) {
                        logger.error(ex, ex);
                    }
                }

            }
            taos.close();
            type = true;
        } catch (Exception e) {
            logger.error("untar file " + tarPath + " failed for " + e, e);
            new File(tarPath).delete();
            type = false;
            throw new Exception("untar file " + tarPath + " failed for " + e);

        } finally {
            return type;
        }

    }

    public static List<String> listFile(File off) {
        List<String> path = new ArrayList<String>();
        if (off.isDirectory()) {
            String[] files = off.list();
            for (String f : files) {
                File file = new File(off.getAbsolutePath() + File.separator + f);
                if (file.isFile()) {
                    path.add(file.getAbsolutePath());
                } else {
                    List<String> tmp = listFile(file.getAbsoluteFile());
                    for (String s : tmp) {
                        path.add(s);
                    }
                }
            }
        } else {
            path.add(off.getAbsolutePath());
        }

        return path;
    }

    public static void main(String[] args) throws Exception {
        String dir = "D:\\123\\111";
        System.out.println(dir.split("\\\\")[dir.split("\\\\").length - 1]);
        GlobalParas.TAR_PATH = "D:\\123";
        GlobalParas.END_PATH = "D:\\123\\222";
        ArrayBlockingQueue<String> b = new ArrayBlockingQueue<>(10);
        Thread t = new Thread(new TarFilePath(b, ""));
        t.start();
        b.put("D:\\123\\111");

//        tar("D:\\123\\222\\sss.tar", "D:\\123\\111");
//        String path = "C:\\Users\\wanglin\\Desktop\\data\\catchFilePath\\2017111922";
//        List<String> files = listFile(new File(path));
//        for (String str : files) {
//            System.out.println(str);
//
//        }
    }

    @Override
    public void run() {
        while (true) {
            if (GlobalParas.TAR_FLAG) {
                break;
            }
            String srcPath;
            try {
                srcPath = this.tarPool.poll(300, TimeUnit.MILLISECONDS);
            } catch (Exception ex) {
                continue;
            }
            if (srcPath != null) {
                File destFile = null;
                try {
//                    logger.info(srcPath);
//                    String tarName = srcPath.split("\\\\")[srcPath.split("\\\\").length - 1] + ".tar";
                    String tarName = srcPath.split(File.separator)[srcPath.split(File.separator).length - 1] + ".tar";
                    String tarPath = GlobalParas.TAR_PATH + File.separator + tarName;
//                    logger.info("tarPath " + tarPath + " srcPath " + srcPath);
                    Boolean type = tar(tarPath, srcPath);
                    destFile = new File(GlobalParas.END_PATH + File.separator + tarName);
                    FileUtils.moveFile(new File(tarPath), destFile);
                    logger.info("move " + tarPath + "  to " + destFile + " success");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    if (srcPath != null) {
                        logger.info(srcPath);
                        this.tarPool.offer(srcPath);
                    }
                }
                try {
//                    String successPath = GlobalParas.catchFilePath + File.separator + "success/" + simp.format(System.currentTimeMillis()) + File.separator;
//                    try {
//                        FileUtils.moveToDirectory(new File(srcPath), new File(successPath), true);
//                    } catch (Exception ex) {
//                        ex.printStackTrace();
//                    }
//                    new File(srcPath).delete();
                    FileUtils.deleteDirectory(new File(srcPath));
                    FileTools.creatTxtFile(destFile.getPath() + ".ok");
                } catch (IOException ex) {
                    ex.printStackTrace();
                    logger.error(ex, ex);
                }
            }
            if (isQuit && this.tarPool.isEmpty()) {
                break;
            }
        }
    }
}
